# -*- coding: utf-8 -*-

"""
Created on Thurs Dec 5 19:17:13 2019

@author: wnma3
"""

import pandas as pd
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA

def normalize(file_path):
    datafile = file_path
    data = pd.read_excel(datafile, header = None) # 读取数据
    
    print((data - data.min())/(data.max() - data.min())) # 最小-最大规范化
    print((data - data.mean())/data.std()) #零-均值规范化
    print(data/10**np.ceil(np.log10(data.abs().max())))  # 小数定标规范化


def cluster(file_path):
    datafile = file_path
    
    data = pd.read_excel(datafile) # 读取数据
    data = data['肝气郁结证型系数'].copy()
    k = 4
    
    # 方法一：等宽离散法
    d1 = pd.cut(data, k, labels = range(k))
    
    # 方法二：等频离散化
    w = [1.0 * i / k for i in range(k + 1)]
    # percentiles表示特定百分位数，同四分位数
    w = data.describe(percentiles = w)[4:4+k+1]
    w[0] = w[0] * (1 - 1e-10)
    d2 = pd.cut(data, w, labels=range(k))
    
    # 方法三：Kmeans聚类
    kmodel = KMeans(n_clusters = k, n_jobs = 4)
    
    kmodel.fit(data.values.reshape(len(data), 1))
    # 输出聚类中心，并且排序
    c = DataFrame(kmodel.cluster_centers_).sort_values(0)
    
    # 相邻两项求中点，作为边界点
    w = DataFrame.rolling(c, 2).mean().iloc[1:]
    # 加上首末边界点
    w = [0] + list(w[0]) + [data.max()]
    d3 = pd.cut(data, w, labels=range(k))
    
    def cluster_plot(d, k):
        plt.figure(figsize=(8, 3))
        for j in range(0, k):
            plt.plot(data[d == j], [j for i in d[d == j]], 'o')
        plt.ylim(-0.5, k - 0.5)
        return plt
        
    cluster_plot(d1, k).show()
    cluster_plot(d2, k).show()
    cluster_plot(d3, k).show()
    
def elect(input_file, output_file):
    data = pd.read_excel(input_file)
    data[u"线损率"] = (data[u"供入电量"] - data[u"供出电量"]) / data[u"供入电量"]
    data.to_excel(output_file, index=False)


def PCAs(input_file, output_file):
    data = pd.read_excel(input_file, header = None)
    
    pca = PCA()
    pca.fit(data)
    # 返回各个模型的特征向量
    pca.components_
    # 返回各个成分各自的方差百分比
    pca.explained_variance_ratio_
    
    # 选取最优主成分个数
    pca = PCA(3)
    pca.fit(data)
    
    # 降维
    low_d = pca.transform(data)
    # 保存结果
    pd.DataFrame(low_d).to_excel(output_file)